package com.suep.business.controller;

import com.suep.business.domain.Coupon;
import com.suep.business.domain.Store;
import com.suep.business.dto.CouponDTO;
import com.suep.business.service.ICouponService;
import com.suep.business.service.IStoreService;
import com.suep.system.config.BaseR;
import com.suep.system.utils.RequestAttributeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/coupon")
public class CouponController {

    @Autowired
    private ICouponService couponService;


    @Autowired
    private IStoreService storeService;



    /**
     * 用户领取优惠券
     * */
    @PostMapping("/receive")
    public BaseR<String> receive(HttpServletRequest request,@RequestBody CouponDTO couponDTO){
        Integer userId=RequestAttributeUtil.getUserIdFromRequest(request);
        couponService.receive(userId,couponDTO);
        return  new BaseR<>().ok("领取优惠券成功");

    }
    /**
     * 用户查询自己拥有的优惠券
     * */
    @GetMapping("/my")
    public BaseR<List<CouponDTO>> getMy(HttpServletRequest request){
        Integer userId=RequestAttributeUtil.getUserIdFromRequest(request);
        return new BaseR<>().ok("获取用户自己拥有的优惠券",couponService.selectMyCoupon(userId));
    }




    @GetMapping
    public BaseR<List<Coupon>> getAll(){
        return new BaseR<>().ok("获取所有商家发行的未过期，且状态为正常的优惠券列表",couponService.selectAllCoupon());
    }

    @GetMapping("/getById")
    public BaseR<Coupon> getById(@RequestParam Integer id) {
        return new BaseR<>().ok("查询成功", couponService.selectCouponById(id));
    }

    @GetMapping("/getByStoreId")
    public BaseR<List<Coupon>> getByStoreId(HttpServletRequest request) {
        Integer userId= RequestAttributeUtil.getUserIdFromRequest(request);
        Store store=storeService.getStoreByUserId(userId);
        Integer storeId=store.getStoreId();
        return new BaseR<>().ok("查询成功", couponService.selectCouponsByStoreId(storeId));
    }

    @PostMapping("/add")
    public BaseR<Integer> add(@RequestBody Coupon coupon, HttpServletRequest request) {
        Integer userId= RequestAttributeUtil.getUserIdFromRequest(request);
        Store store=storeService.getStoreByUserId(userId);
        Integer storeId=store.getStoreId();
        //TODO:这里应该还需要一个工具类使用某个算法为优惠券的code生成唯一码，但这个可以很后面再补充上去
        coupon.setStoreId(storeId);
        return new BaseR<>().ok("插入成功", couponService.insertCoupon(coupon));
    }


    @PutMapping("/change")
    public BaseR<Integer> change(@RequestBody Coupon coupon) {
        return new BaseR<>().ok("更新成功", couponService.updateCoupon(coupon));
    }

    @DeleteMapping("/remove")
    public BaseR<Integer> remove(@RequestParam Integer id) {
        return new BaseR<>().ok("删除成功", couponService.deleteCouponById(id));
    }
}